from PySide6.QtWidgets import (QFrame, QGridLayout, QWidget, QPushButton, QVBoxLayout,
            QButtonGroup,QDialog,QDialogButtonBox,QCompleter,QMessageBox,QScrollArea,QLabel,QComboBox)
from PySide6.QtCore import Qt,QTimer,Signal,QStringListModel
import configparser
from qfluentwidgets import SearchLineEdit

# region 宠物选择对话框
class PetSelectionDialog(QDialog):
    """宠物选择对话框"""
    pet_selected = Signal(str)  # 传递选中的宠物名称
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.db=parent.db
        self.ui_init()
        self.setup_autocompletion()

    def ui_init(self):
        self.setWindowTitle("选择宠物")
        self.setFixedSize(400, 300)
        
        layout = QVBoxLayout(self)
        
        # 搜索框
        self.searchEdit = SearchLineEdit(self)
        self.searchEdit.setPlaceholderText("搜索宠物...")
        layout.addWidget(self.searchEdit)
        
        # 按钮区
        buttonBox = QDialogButtonBox(
            QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel,
            Qt.Orientation.Horizontal, self
        )
        buttonBox.accepted.connect(self.acceptSelection)
        buttonBox.rejected.connect(self.reject)
        layout.addWidget(buttonBox)

    def setup_autocompletion(self):
        """设置自动补全功能（优化版）"""
        # 1. 初始化自动补全
        self.model = QStringListModel()

        self.completer = QCompleter(self)        
        self.completer.setModel(self.model)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setFilterMode(Qt.MatchContains)
        
        self.searchEdit.setCompleter(self.completer)
        
        self.searchEdit.textChanged.connect(self.update_autocompletion)
    def update_autocompletion(self,search_text):
        """从数据库获取自动补全数据"""
        if not search_text:
            self.model.setStringList([])
            return
            
        try:
            # 优化：只查询名字字段
            pet_infos = self.db.search_pets(name=search_text, all_pets=True) 
            
            # 存储新的自动补全项（名字倒序）
            unique_names = []
            for pet_info in reversed(pet_infos):
                pet_name = pet_info[0]  # 假设第一个元素是名字
                unique_names.append(pet_name)
            
            # 更新模型
            self.model.setStringList(unique_names)
        
            # 安全触发下拉框显示（关键修改）
            if unique_names and self.searchEdit.isEnabled():
                QTimer.singleShot(50, self.safe_show_completer)
                
        except Exception as e:
            print(f"自动补全查询错误: {e}")

    def safe_show_completer(self):
        """安全显示补全下拉框"""
        # 双重检查控件有效性
        if (self.searchEdit.isVisible() and 
            self.searchEdit.isEnabled() and
            not self.searchEdit.text().strip() and
            self.completer):
            
            # 设置焦点到搜索框（确保下拉框能显示）
            self.searchEdit.setFocus()
            
            # 安全调用complete()
            try:
                if len(self.completion_model.stringList()) > 0:
                    self.completer.setCompletionPrefix(self.searchEdit.text())
                    self.completer.complete()
            except RuntimeError:
                # 处理对象已被销毁的情况
                pass

    def acceptSelection(self):
        """确认选择并关闭对话框"""
        selected_pet = self.searchEdit.text()
        self.pet_selected.emit(selected_pet)
        self.close()
# endregion

# region 显示宠物战斗界面
class ShowPetBattleWidget(QFrame):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.db=parent.db
        self.setObjectName("ShowPetBattleWidget")
        self.ui_init()
        self.get_battle_team_config()
        self.setup_autocompletion()

# region 界面初始化
    def ui_init(self):
                # 主垂直布局
        self.vBoxLayout = QVBoxLayout(self)
        self.vBoxLayout.setSpacing(20)  # 设置控件间间距
        
        # 创建搜索框
        self.searchEdit = SearchLineEdit(self)
        self.searchEdit.setPlaceholderText("搜索宠物...")
        self.searchEdit.searchSignal.connect(self.select_battle_pet)
        
        # 创建网格布局区域 (3x3)
        self.gridWidget = QWidget()
        self.gridLayout = QGridLayout(self.gridWidget)
        self.gridLayout.setSpacing(10)  # 网格内控件间距
        
                # 创建按钮组管理宠物按钮
        self.petButtonGroup = QButtonGroup(self)
        self.petButtonGroup.setExclusive(True)  # 允许多选
        # 添加6个宠物按钮
        self.pet_buttons = []
        for i in range(6):
            row = i // 3
            col = i % 3
            
            # 直接创建按钮，而不是使用createPetWidget
            btn = QPushButton(f"宠物 {i+1}")
            btn.setObjectName(f"pet_{i+1}")
            btn.setCheckable(True)  # 设置为可选中状态
            
            # 添加到布局和按钮组
            self.gridLayout.addWidget(btn, row, col)
            self.pet_buttons.append(btn)
            self.petButtonGroup.addButton(btn)
        self.modeCombo = QComboBox()
        self.modeCombo.addItems(["天梯", "系别"])
        self.modeCombo.currentIndexChanged.connect(self.get_battle_team_config)
        self.gridLayout.addWidget(self.modeCombo, 2, 0) 
        
        # 添加保存按钮（占据第2行第1-2列）
        self.saveButton = QPushButton("保存配置")
        self.saveButton.setObjectName("saveButton")
        self.gridLayout.addWidget(self.saveButton, 2, 2)  # row, col, rowSpan, colSpan
        
        # 创建底部空白区域
        self.bottomWidget = QWidget()
        self.bottomWidget.setMinimumHeight(30)
        
        # 将组件添加到垂直布局
        self.vBoxLayout.addWidget(self.gridWidget)
        self.vBoxLayout.addWidget(self.searchEdit)
        self.vBoxLayout.addWidget(self.bottomWidget)

        self.petButtonGroup.buttonClicked.connect(self.onPetButtonClicked)
        self.saveButton.clicked.connect(self.onSaveClicked)
# endregion

# region 获取队伍配置
    def get_battle_team_config(self):
        """
        获取对战队伍配置
        """
        file_path = "config/battle_teams.ini"
        config = configparser.ConfigParser()
        config.read(file_path, encoding='utf-8')
        pets=[]
        if self.modeCombo.currentText() == "天梯":
            section_name = "Team_tt"
        elif self.modeCombo.currentText() == "系别":
            section_name = "Team_xb"
        if config.has_section(section_name):
            for i in range(1, 7):
                pet_key = f"pet{i}"
                if config.has_option(section_name, pet_key):
                    pet_name = config.get(section_name, pet_key)
                    pets.append(pet_name)

        for i in range(6):
            if i < len(self.pet_buttons):
                btn = self.pet_buttons[i]
                btn.setText(pets[i] if i < len(pets) else "")
                # 同步更新选中状态样式
                btn.setChecked(bool(pets[i]))
        if hasattr(self, "pet_1"):
            self.battle_pet = self.pet_1.text()
# endregion

# region 更改上场宠物
    def onPetButtonClicked(self,button):

        """宠物按钮点击事件"""
        self.current_button = button
        self.showPetSelectionDialog()

    def showPetSelectionDialog(self):
        """显示宠物选择对话框"""
        dialog = PetSelectionDialog(self)
        dialog.pet_selected.connect(self.updatePetButtonText)
        dialog.exec_()

    def updatePetButtonText(self, pet_name):
        """更新按钮显示的宠物名称"""
        if self.current_button:
            self.current_button.setText(pet_name)
            # 记录选中的宠物数据（实际应用中可能存储更多信息）
            self.current_button.setProperty("selected_pet", pet_name)
  # endregion

  # region 保存
    def onSaveClicked(self):
        """处理保存按钮点击事件"""
        file_path = "config/battle_teams.ini"
        config = configparser.ConfigParser()
        config.read(file_path, encoding='utf-8')
        if self.modeCombo.currentText() == "天梯":
            section_name = "Team_tt"
        elif self.modeCombo.currentText() == "系别":
            section_name = "Team_xb"
        # 如果 Team1 节不存在，则创建
        if not config.has_section(section_name):
            config.add_section(section_name)
        # 遍历按钮，获取宠物名字并写入配
        for i in range(1, 7):
            pet_name=self.pet_buttons[i-1].text()
            config.set(section_name, f"pet{i}", pet_name)
        # 将配置写入文件
        with open(file_path, 'w', encoding='utf-8') as configfile:
            config.write(configfile)
            QMessageBox.information(self, "提示", "阵容保存成功")
# endregion

 #region 搜索框补全
    def setup_autocompletion(self):
        """设置自动补全功能（优化版）"""
        # 1. 初始化自动补全
        self.model = QStringListModel()

        self.completer = QCompleter(self)        
        self.completer.setModel(self.model)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setFilterMode(Qt.MatchContains)
        
        self.searchEdit.setCompleter(self.completer)
        
        self.searchEdit.textChanged.connect(self.update_autocompletion)
    def update_autocompletion(self,search_text):
        """从数据库获取自动补全数据"""
        if not search_text:
            self.model.setStringList([])
            return
            
        try:
            # 优化：只查询名字字段
            pet_infos = self.db.search_pets(name=search_text, all_pets=True) 
            
            # 存储新的自动补全项（名字倒序）
            unique_names = []
            for pet_info in reversed(pet_infos):
                pet_name = pet_info[0]  # 假设第一个元素是名字
                unique_names.append(pet_name)
            
            # 更新模型
            self.model.setStringList(unique_names)
        
            # 安全触发下拉框显示（关键修改）
            if unique_names and self.searchEdit.isEnabled():
                QTimer.singleShot(50, self.safe_show_completer)
                
        except Exception as e:
            print(f"自动补全查询错误: {e}")

    def safe_show_completer(self):
        """安全显示补全下拉框"""
        # 双重检查控件有效性
        if (self.searchEdit.isVisible() and 
            self.searchEdit.isEnabled() and
            not self.searchEdit.text().strip() and
            self.completer):
            
            # 设置焦点到搜索框（确保下拉框能显示）
            self.searchEdit.setFocus()
            
            # 安全调用complete()
            try:
                if len(self.completion_model.stringList()) > 0:
                    self.completer.setCompletionPrefix(self.searchEdit.text())
                    self.completer.complete()
            except RuntimeError:
                # 处理对象已被销毁的情况
                pass
# endregion

# region 选择对面的宠物
    def select_battle_pet(self):
        """
        选择敌方宠物
        """
        opponent_pet_name  = self.searchEdit.text()

        our_pet_team = []
        for i in range(6):
            our_pet_team.append(self.pet_buttons[i].text())

        try:
            strategies_queue = self.db.get_battle_strategies(opponent_pet_name, our_pet_team)
            layout = QVBoxLayout()

            # 创建一个 QWidget 作为滚动区域的内容
            scroll_content = QWidget()
            scroll_content.setLayout(layout)

            # 创建 QScrollArea 并设置内容
            scroll_area = QScrollArea()
            scroll_area.setWidget(scroll_content)
            scroll_area.setWidgetResizable(True)
            scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

            # 清空 w_battle 原有内容
            w_battle = self.bottomWidget
            
            # 清理现有布局内容
            if w_battle.layout() is not None:
                # 获取当前布局并清除所有子部件
                existing_layout = w_battle.layout()
                while existing_layout.count():
                    item = existing_layout.takeAt(0)
                    widget = item.widget()
                    if widget:
                        widget.deleteLater()
            else:
                # 没有布局时创建新布局
                w_battle.setLayout(QVBoxLayout())

            # 将 QScrollArea 添加到清理后的布局中
            w_battle.layout().addWidget(scroll_area)

            # 处理队列中的数据
            if not strategies_queue.empty():
                while not strategies_queue.empty():
                    flag, data = strategies_queue.get()
                    opponent_pet_name=data['opponent_pet_name']
                    our_pet_name = data['our_pet_name']
                    turn_order = data['turn_order']
                    outcome = data['outcome']
                    strategy_description = data['strategy_description']
                    success_count = data['success_count']

                    # 转换上场顺序文本
                    turn_order_text = {
                        -1: "后发上场",
                        0: "同时上场",
                        1: "提前站场"
                    }.get(turn_order, str(turn_order))
                    if flag == 1 or flag==3:
                        info_label = QLabel(
                            f"对方宠物:{opponent_pet_name}<br>"
                            f"我方宠物: {our_pet_name}<br>"
                            f"上场顺序: {turn_order_text}<br>"
                            f"结&nbsp;&nbsp;&nbsp;&nbsp;果: {outcome}<br>"
                            f"策略描述: {strategy_description}<br>"
                            f"记录次数：{success_count}"
                        )
                    elif flag==2:
                        info_label = QLabel(
                            f"对方宠物:{our_pet_name}<br>"
                            f"我方宠物: {opponent_pet_name}<br>"
                            f"上场顺序: {turn_order_text}<br>"
                            f"结&nbsp;&nbsp;&nbsp;&nbsp;果: {outcome}<br>"
                            f"记录次数：{success_count}"
                        )
                    info_label.setWordWrap(True)
                    info_label.setAlignment(Qt.AlignLeft | Qt.AlignTop)

                    # 设置颜色样式
                    if flag == 1:
                        bg_color = "#45ff45"
                    elif flag==2:
                        bg_color = "#ff3f3f"
                    else:
                        bg_color = "#43bdff"
                    info_label.setStyleSheet(f"""
                        font-size: 18px;
                        background-color: {bg_color};
                        padding: 5px;
                        margin: 2px;
                    """)

                    layout.addWidget(info_label)
            else:
                print("未获取到战斗策略数据")
        except Exception as e:
            print("获取战斗策略失败:", e)
            self._show_error("获取战斗策略失败", str(e))
